package sentinel.Ribbon;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import spring.cloud.Utils.R;

/**
 * @author cyt
 * @create 2020-06-06 8:57
 */
@RestController
public class testOneController {

    @Autowired
    RestTemplate restTemplate;

    private String add = "http://nacos-payment-provider";


    /**
     * fallback 使用来处理代码逻辑上的兜底
     * blockHandler 用来处理 配置上的兜底
     *
     * @param id
     * @return
     */
    @GetMapping("/fallback/{id}")
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")
    public R fallback(@PathVariable("id") Long id) {
        R forObject = restTemplate.getForObject(add + "/provider" + "/paymentSQL/{id}", R.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        } else if (forObject.getData().get("payment") == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return forObject;
    }

    public R handlerFallback(@PathVariable("id") Long id, Throwable throwable) {
        Payment payment = new Payment(id, "");
        return R.error();
    }

    //blockHandler
    public R blockHandler(@PathVariable("id") Long id, BlockException blockException) {
        Payment payment = new Payment(id, "null");
        return R.error();
    }

}
